package org.west.sky.frame.activiti.study.chapter13;

import lombok.SneakyThrows;
import org.activiti.engine.history.HistoricProcessInstance;
import org.activiti.engine.repository.ProcessDefinition;
import org.activiti.engine.runtime.Execution;
import org.activiti.engine.runtime.ProcessInstance;
import org.activiti.engine.task.Task;
import org.west.sky.frame.activiti.study.util.ActivitiEngineUtil;

import java.util.HashMap;
import java.util.Map;

/**
 * author: chz
 * date: 2025/3/12
 * description: 接收任务
 */
public class RunDemo13_3_2 extends ActivitiEngineUtil {

    public static void main(String[] args) {
        RunDemo13_3_2 runDemo13_1_1 = new RunDemo13_3_2();
        runDemo13_1_1.deploy();
    }

    @SneakyThrows
    private void deploy() {
        loadActivitiConfigAndInitEngine("activiti.cfg.xml");
        //部署流程
        ProcessDefinition processDefinition = deployByClassPathResource("processes/chapter13/Chapter13_3_2.bpmn20.xml");
        ProcessInstance processInstance = runtimeService.startProcessInstanceById(processDefinition.getId());
        //完成任务
        Task task_1 = taskService.createTaskQuery().processInstanceId(processInstance.getId()).singleResult();
        System.out.println("====当前流程：" + processInstance.getId() + "进行到：" + task_1.getName());
        taskService.complete(task_1.getId());

        Task task_2 = taskService.createTaskQuery().processInstanceId(processInstance.getId()).singleResult();
        System.out.println("====当前流程：" + processInstance.getId() + "进行到：" + task_2.getName());
        taskService.complete(task_2.getId());

        Execution execution = runtimeService.createExecutionQuery().processInstanceId(processInstance.getId())
                .activityId("sid-8c153f08-59a0-4ceb-a803-030f4eefb906").singleResult();
        System.out.println("====当前执行id：" + execution.getId() + ",当前执行名称：" + execution.getName());
        Map<String, Object> variables = new HashMap<>();
        variables.put("approveResult", "审核通过！！");
        runtimeService.trigger(execution.getId(), variables);

        HistoricProcessInstance historicProcessInstance = historyService.createHistoricProcessInstanceQuery()
                .processInstanceId(processInstance.getId()).singleResult();
        if (historicProcessInstance != null) {
            System.out.println("====流程结束：" + sdf.format(historicProcessInstance.getEndTime()));
        } else {
            System.out.println("====流程未结束");
        }

        closeEngine();
    }
}
